﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using PulsePrototype.Messages;
using PulsePrototype.Messages.DescriptionMessages;
using PulsePrototype.Messages.PositionMessages;

namespace PulsePrototype.PulseManagers
{
    public class RenderComponent : BaseComponent
    {
        private RenderDescription description;
        private Matrix scaleMatrix = Matrix.Identity;

        public RenderDescription Description
        {
            get { return description; }
        }

        protected override String GetName()
        {
            return "Render";
        }

        public RenderComponent(BaseEntity ParentEntity, String ModelName) :
            base(ParentEntity)
        {
            Initialize();
            LoadModel(ModelName);
        }

        protected override void Initialize()
        {
            description = new RenderDescription(this);
            description.worldTransform = this.scaleMatrix * this.Parent.rotation 
                * Matrix.CreateTranslation(this.Parent.position);
            
            base.Initialize();
        }

        private void LoadModel(String modelName)
        {
            description.texture = this.Parent.Manager.Content.Load<Texture2D>(modelName);
            description.origin = new Vector2((float)description.texture.Width / 2f, (float)description.texture.Height / 2f);
        }

        public override bool SendMessage(BaseMessage msg)
        {
            // Entity has a switch for any messages it cares about
            switch (msg.messageType)
            {
                case MessageType.SetRotation:
                    {
                        MsgSetRotation msgSetRot = msg as MsgSetRotation;
                        Description.rotation = msgSetRot.rotation;

                        // Console.WriteLine("RenderComponent handling SetPosition");
                    }
                    break;
                case MessageType.SetPosition:
                    {
                        MsgSetPosition msgSetPos = msg as MsgSetPosition;
                        Description.position = new Vector3(msgSetPos.x, msgSetPos.y, msgSetPos.z);
                    }
                    break;
                default:
                    return base.SendMessage(msg);
            }

            return true;

        }

        public override void Update(GameTime gameTime)
        {
            //description.worldTransform = this.scaleMatrix * this.Parent.rotation * Matrix.CreateTranslation(this.Parent.position);
            //description.position = this.Parent.position;
        }

        public override void Draw(GameTime gameTime, List<RenderDescription> renderDescriptions)
        {
            renderDescriptions.Add(description);
        }

    }
}
